<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-SpringCloud-2-Eureka - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="什么是服务注册中心 服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息，譬如提供者url 串、路由信息等。 服" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-SpringCloud-2-Eureka - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-SpringCloud-2-Eureka" />
<meta property="og:description" content="什么是服务注册中心 服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息，譬如提供者url 串、路由信息等。 服" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-2-eureka/" />
<meta property="article:published_time" content="2019-08-25T11:18:30+08:00" />
<meta property="article:modified_time" content="2019-08-25T11:18:30+08:00" />
<meta itemprop="name" content="Java-framework-SpringCloud-2-Eureka">
<meta itemprop="description" content="什么是服务注册中心 服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息，譬如提供者url 串、路由信息等。 服">
<meta itemprop="datePublished" content="2019-08-25T11:18:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-25T11:18:30&#43;08:00" />
<meta itemprop="wordCount" content="6524">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-SpringCloud-2-Eureka"/>
<meta name="twitter:description" content="什么是服务注册中心 服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息，譬如提供者url 串、路由信息等。 服"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-springcloud-2-eureka/"
    >Java-framework-SpringCloud-2-Eureka</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-2-eureka/" class="article-date">
  <time datetime="2019-08-25 11:18:30 &#43;0800 CST" itemprop="datePublished">2019-08-25</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-springcloud-2-eureka/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 6524words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 14minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="什么是服务注册中心">什么是服务注册中心</h1>
<p>服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息，譬如提供者url 串、路由信息等。</p>
<p>服务注册中心是SOA 架构中最基础的设施之一。</p>
<h2 id="服务注册中心的作用">服务注册中心的作用</h2>
<p>1）作用：</p>
<ul>
<li>服务的注册</li>
<li>服务的发现</li>
</ul>
<p>类比：QQ群，有人加入群就是注册服务，能不能加入群取决于管理员，每个群成员就是已注册的服务。</p>
<p>2）常见的注册中心</p>
<ul>
<li>Dubbo 的注册中心 Zookeeper</li>
<li>SringCloud 的注册中心 Eureka、Consul</li>
</ul>
<p>3）服务注册中心解决了以下问题：</p>
<ol>
<li>服务管理</li>
<li>服务的依赖关系管理</li>
</ol>
<p><!-- raw HTML omitted --></p>
<p>4）什么是 Eureka 注册中心</p>
<p>Eureka 是 Netflix 开发的服务发现组件，本身是一个基于 REST 的服务。Spring Cloud 将它集成在其子项目 spring-cloud-netflix 中，以实现Spring Cloud 的服务注册于发现，同时还提供了负载均衡、故障转移等能力。</p>
<p>Eureka 注册中心三种角色</p>
<ul>
<li>Eureka Server：通过Register、Get、Renew 等接口提供服务的注册和发现。</li>
<li>Application Service (Service Provider)：服务提供方，把自身的服务实例注册到 Eureka Server 中</li>
<li>Application Client (Service Consumer)：服务调用方，通过 Eureka Server 获取服务列表，消费服务。</li>
</ul>
<p>参考：</p>
<p><!-- raw HTML omitted --></p>
<p>总结：服务提供者需要注册到Eureka，消费者则不必须；可以使用<code>register-with-eureka: false/true</code>来控制</p>
<h1 id="eureka-入门案例">Eureka 入门案例</h1>
<p>1）创建项目</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708105739.png" alt=""></p>
<p>2）添加依赖</p>
<pre><code class="language-xml">    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
                &lt;version&gt;Dalston.SR5&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;!--eureka--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka-server&lt;/artifactId&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
</code></pre>
<p>小巧门：这些依赖在官方文档很难找到，可以通过官网的Quick start，下载后查看pom文件即可：https://start.spring.io/</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708105758.png" alt=""></p>
<p>3）启动类</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaServer
public class EurekaApp {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class, args);
    }
}
</code></pre>
<p>4）全局配置文件</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8761

#是否将自己注册到eureka中，默认true
eureka.client.register-with-eureka=false
#是否从eureka-server中获取服务注册信息，默认true
eureka.client.fetch-registry=false

eureka.instance.prefer-ip-address=true
</code></pre>
<p>注意：两个false的设置是重点，作用是“不将自己注册到eureka，而是自己作为服务，以供其它服务注册到自己”</p>
<p>另外，将<code>eureka.instance.prefer-ip-address=true</code>配置上，有大用 20200702</p>
<p>5）通过 http://localhost:8761/ 查看eureka-server管理平台</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708105819.png" alt=""></p>
<h1 id="eureka-集群高可用的eureka">Eureka 集群（高可用的eureka）</h1>
<p>防止一个注册中心挂了，其它服务注册不进来，所以需要搭建一个高可用的eureka，即集群。</p>
<h2 id="一创建项目">一、创建项目</h2>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708105839.png" alt=""></p>
<h2 id="二全局配置文件">二、全局配置文件</h2>
<p>知识点：</p>
<pre><code class="language-properties">#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka2
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka1:8761/eureka/
</code></pre>
<p>在搭建Eureka 集群时，需要添加多个配置文件，并且使用SpringBoot 的多环境配置方
式。集群中需要多少节点就添加多少个配置文件。</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708105919.png" alt=""></p>
<p>eureka1：</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8761

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka1
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka2:8761/eureka/
</code></pre>
<p>eureka2：</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8761

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka2
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka1:8761/eureka/
</code></pre>
<hr>
<p>启动类：</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaServer
public class EurekaApp {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class, args);
    }
}
</code></pre>
<h2 id="三添加日志文件logbackxml">三、添加日志文件logback.xml</h2>
<h2 id="四集群配置">四、集群配置</h2>
<p>部署环境：两台linux，都需要安装jdk1.8，正确配置JAVA环境变量，IP分别是 192.168.12.132、192.168.12.133</p>
<p>注意：需要关闭防火墙，或者是开放8761 端口</p>
<p>1）将项目打包</p>
<p><code>02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar</code></p>
<p>2）将项目jar包上传到两台Linux</p>
<p>将<code>02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar</code>上传至 192.168.12.132 /root/temp目录下</p>
<p>将<code>02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar</code>上传至 192.168.12.133 /root/temp目录下</p>
<p>3）在linux上操作</p>
<p>192.168.12.132：</p>
<pre><code>[root@localhost ~]# cd /usr/local
[root@localhost ~]# mkdir eureka
[root@localhost ~]# cp /root/temp/02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar /usr/local/eureka -f

[root@localhost ~]# cd /usr/local/eureka
[root@localhost ~]# vim server.sh
</code></pre>
<p>server.sh如下：</p>
<pre><code class="language-sh">#!/bin/bash
 
cd `dirname $0`
 
CUR_SHELL_DIR=`pwd`
CUR_SHELL_NAME=`basename ${BASH_SOURCE}`
 
JAR_NAME=&quot;项目名称&quot;
JAR_PATH=$CUR_SHELL_DIR/$JAR_NAME
 
#JAVA_MEM_OPTS=&quot; -server -Xms1024m -Xmx1024m -XX:PermSize=128m&quot;
JAVA_MEM_OPTS=&quot;&quot;
 
SPRING_PROFILES_ACTIV=&quot;-Dspring.profiles.active=配置文件变量名称&quot;
#SPRING_PROFILES_ACTIV=&quot;&quot;
LOG_DIR=$CUR_SHELL_DIR/logs
LOG_PATH=$LOG_DIR/${JAR_NAME%..log
 
echo_help()
{
    echo -e &quot;syntax: sh $CUR_SHELL_NAME start|stop&quot;
}
 
if [ -z $1 ];then
    echo_help
    exit 1
fi
 
if [ ! -d &quot;$LOG_DIR&quot; ];then
    mkdir &quot;$LOG_DIR&quot;
fi
 
if [ ! -f &quot;$LOG_PATH&quot; ];then
    touch &quot;$LOG_DIR&quot;
fi
 
if [ &quot;$1&quot; == &quot;start&quot; ];then
 
    # check server
    PIDS=`ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}'`
    if [ -n &quot;$PIDS&quot; ]; then
        echo -e &quot;ERROR: The $JAR_NAME already started and the PID is ${PIDS}.&quot;
        exit 1
    fi
 
    echo &quot;Starting the $JAR_NAME...&quot;
 
    # start
    nohup java $JAVA_MEM_OPTS -jar $SPRING_PROFILES_ACTIV $JAR_PATH &gt;&gt; $LOG_PATH 2&gt;&amp;1 &amp;
 
    COUNT=0
    while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=`ps  --no-heading -C java -f --width 1000 | grep &quot;$JAR_NAME&quot; | awk '{print $2}' | wc -l`
        if [ $COUNT -gt 0 ]; then
            break
        fi
    done
    PIDS=`ps  --no-heading -C java -f --width 1000 | grep &quot;$JAR_NAME&quot; | awk '{print $2}'`
    echo &quot;${JAR_NAME} Started and the PID is ${PIDS}.&quot;
    echo &quot;You can check the log file in ${LOG_PATH} for details.&quot;
 
elif [ &quot;$1&quot; == &quot;stop&quot; ];then
 
    PIDS=`ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}'`
    if [ -z &quot;$PIDS&quot; ]; then
        echo &quot;ERROR:The $JAR_NAME does not started!&quot;
        exit 1
    fi
 
    echo -e &quot;Stopping the $JAR_NAME...&quot;
 
    for PID in $PIDS; do
        kill $PID &gt; /dev/null 2&gt;&amp;1
    done
 
    COUNT=0
    while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=1
        for PID in $PIDS ; do
            PID_EXIST=`ps --no-heading -p $PID`
            if [ -n &quot;$PID_EXIST&quot; ]; then
                COUNT=0
                break
            fi
        done
    done
 
    echo -e &quot;${JAR_NAME} Stopped and the PID is ${PIDS}.&quot;
else
    echo_help
    exit 1
fi
</code></pre>
<p>将文件中的“项目名称”、“配置文件变量名称”分为改为“02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar”、“eureka1”</p>
<p>更改权限，使文件可执行</p>
<pre><code class="language-sh">[root@localhost ~]# chmod -R 755 server.sh
</code></pre>
<p>修改host文件</p>
<pre><code class="language-shell">[root@localhost ~]# vim /etc/hosts
</code></pre>
<p>添加以下配置</p>
<pre><code class="language-tex">192.168.12.132 eureka1
192.168.12.133 eureka2
</code></pre>
<hr>
<p>192.168.12.133：</p>
<p>也作相同的操作，不同处是server.sh文件中“项目名称”、“配置文件变量名称”配置如下</p>
<p>“02-spring-cloud-eureka-server-ha-1.0-SNAPSHOT.jar”、“eureka2”</p>
<p>4）启动eureka注册中心</p>
<pre><code>[root@localhost ~]# cd /usr/local/eureka
[root@localhost ~]# ./server.sh start

[root@localhost ~]# ./server.sh stop
</code></pre>
<p>在linux上启动不成功 ——20190621</p>
<p>转为在windows上，用idea启动两个应用</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708110007.png" alt=""></p>
<p>windows下同样需要配置hsot文件</p>
<pre><code>127.0.0.1 eureka1
127.0.0.1 eureka2
</code></pre>
<p>因在同一电脑上，需要修改 application-eureka1.properties、application-eureka2.properties的端口号</p>
<p>application-eureka1.properties</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8761

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka1
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka2:8762/eureka/
</code></pre>
<p>application-eureka2.properties</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8762

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka2
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka1:8761/eureka/
</code></pre>
<p>参考：https://blog.csdn.net/u011531425/article/details/81713441</p>
<p>5）页面上访问 http://localhost:8761/ ——windwos上集群</p>
<p>项目代码：https://github.com/wolf-lea/spring-cloud/tree/master/02-spring-cloud-eureka-server-ha</p>
<h1 id="在高可用的eureka-注册中心中构建provider-服务">在高可用的Eureka 注册中心中构建provider 服务</h1>
<p>以客户端方式构建服务</p>
<p>1）创建项目</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708110034.png" alt=""></p>
<p>2）导入依赖</p>
<pre><code class="language-xml">    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
                &lt;version&gt;Dalston.SR5&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;!--eureka--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka&lt;/artifactId&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
</code></pre>
<p>注意：依赖是<code>spring-cloud-starter-eureka</code></p>
<p>3）引导类</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient
public class EurekaApp {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class, args);
    }
}
</code></pre>
<p>4）全局配置文件</p>
<pre><code class="language-properties">spring.application.name=eureka-provider
server.port=9090

#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka1:8761/eureka/,http://eureka2:8762/eureka/
</code></pre>
<p>5）修改windows下host文件</p>
<pre><code>
</code></pre>
<p>6）编写一个controller、pojo</p>
<pre><code class="language-java">@RestController
@RequestMapping(&quot;/user&quot;)
public class UserController {

    @RequestMapping(&quot;/listUsers&quot;)
    public List&lt;User&gt; listUsers(){
        List&lt;User&gt; list = new ArrayList();
        list.add(new User(1, &quot;zhangsan&quot;, 20));
        list.add(new User(2, &quot;lisi&quot;, 22));
        list.add(new User(3, &quot;wangwu&quot;, 20));
        return list;
    }
}
</code></pre>
<pre><code class="language-java">public class User {
    private int userid;
    private String username;
    private int userage;

    public User() {
    }

    public User(int userid, String username, int userage) {
        this.userid = userid;
        this.username = username;
        this.userage = userage;
    }
    
    //get/setter...
</code></pre>
<p>7）启动引导类</p>
<p>访问 http://localhost:8761/ ，在服务注册中心就多了刚刚的服务</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708110105.png" alt=""></p>
<h1 id="在高可用的eureka-注册中心中构建consumer-服务">在高可用的Eureka 注册中心中构建consumer 服务</h1>
<p>1）创建项目</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708110129.png" alt=""></p>
<p>2）全局配置文件</p>
<p>注意：服务的provider和consumer都需要在eureka注册。</p>
<p>配置文件中的<code>defaultZone</code>跟provider一样</p>
<pre><code class="language-properties">spring.application.name=eureka-consumer
server.port=9091

#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://eureka1:8761/eureka/,http://eureka2:8762/eureka/
</code></pre>
<p>3）在Service 中完成服务的调用</p>
<pre><code class="language-java">@Service
public class UserService {
    @Autowired
    private LoadBalancerClient loadBalancerClient;//ribbon负载均衡器

    public List&lt;User&gt; listUsers() {
        //选择调用的服务名称
        //ServiceInstance封装了服务的IP、端口
        ServiceInstance si = this.loadBalancerClient.choose(&quot;eureka-provider&quot;);

        //拼接服务的路径，http://localhost:9090/user/listUsers
        StringBuffer sb = new StringBuffer();
        sb.append(&quot;http://&quot;).append(si.getHost()).append(&quot;:&quot;).append(si.getPort())
                .append(&quot;/user/listUsers&quot;);

        RestTemplate rt = new RestTemplate();
        ParameterizedTypeReference&lt;List&lt;User&gt;&gt; type = new ParameterizedTypeReference&lt;List&lt;User&gt;&gt;() {
        };
        ResponseEntity&lt;List&lt;User&gt;&gt; response =
                rt.exchange(sb.toString(), HttpMethod.GET, null, type);
        List&lt;User&gt; userList = response.getBody();
        return userList;
    }
}
</code></pre>
<p>4）编写controller</p>
<pre><code class="language-java">@RestController
@RequestMapping(&quot;/user&quot;)
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(&quot;/listUsers&quot;)
    public List&lt;User&gt; listUsers(){
        List&lt;User&gt; list = userService.listUsers();
        return list;
    }
}
</code></pre>
<p>5）测试</p>
<p>启动eureka1、eureka2、eureka-provider、eureka-consumer，访问 http://localhost:9091/user/listUsers</p>
<p>返回以下数据</p>
<pre><code>[{&quot;userid&quot;:1,&quot;username&quot;:&quot;zhangsan&quot;,&quot;userage&quot;:20},{&quot;userid&quot;:2,&quot;username&quot;:&quot;lisi&quot;,&quot;userage&quot;:22},{&quot;userid&quot;:3,&quot;username&quot;:&quot;wangwu&quot;,&quot;userage&quot;:20}]
</code></pre>
<h1 id="eureka-注册中心架构原理">Eureka 注册中心架构原理</h1>
<p>Eureka 架构图</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708111852.png" alt=""></p>
<p>参考：https://github.com/Netflix/eureka/wiki/Eureka-at-a-glance</p>
<ul>
<li>Register(服务注册)：把自己的IP 和端口注册给Eureka。</li>
<li>Renew(服务续约)：发送心跳包，每30 秒发送一次。告诉Eureka 自己还活着。</li>
<li>Cancel(服务下线)：当provider 关闭时会向Eureka 发送消息，把自己从服务列表中删除。防止consumer 调用到不存在的服务。</li>
<li>Get Registry(获取服务注册列表)：获取其他服务列表。</li>
<li>Replicate(集群中数据同步)：eureka 集群中的数据复制与同步。</li>
<li>Make Remote Call(远程调用)：完成服务的远程调用。</li>
</ul>
<h1 id="eureka与zookeeper-的区别">Eureka与Zookeeper 的区别</h1>
<p>两个框架都是基于分布式CAP 定理</p>
<h2 id="什么是cap-原则">什么是CAP 原则</h2>
<p>CAP 原则又称CAP 定理，指的是在一个分布式系统中，Consistency（一致性）、
Availability（可用性）、Partition tolerance（分区容错性），三者不可兼得。</p>
<p>CAP 由Eric Brewer 在2000 年PODC 会议上提出。该猜想在提出两年后被证明成
立，成为我们熟知的CAP 定理</p>
<p>分布式系统CAP 定理</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr>
<td>C <!-- raw HTML omitted --> 数据一致性 <!-- raw HTML omitted --> (Consistency)</td>
<td>也叫做数据原子性 <!-- raw HTML omitted -->系统在执行某项操作后仍然处于一致的状态。<!-- raw HTML omitted -->在分布式系统中，更新操作执行成功后所有的用户都应该读到最新的值，<!-- raw HTML omitted -->这样的系统被认为是具有强一致性的。等同于所有节点访问同一份最新的数据副本。</td>
</tr>
<tr>
<td>A <!-- raw HTML omitted --> 服务可用性 <!-- raw HTML omitted --> (Availablity)</td>
<td>每一个操作总是能够在一定的时间内返回结果，这里需要注意的是&quot;一定时间内&quot;和&quot;返回结果&rdquo;。<!-- raw HTML omitted -->一定时间内指的是，在可以容忍的范围内返回结果，结果可以是成功或者是失败。</td>
</tr>
<tr>
<td>P <!-- raw HTML omitted --> 分区容错性 <!-- raw HTML omitted --> (Partition-torlerance)</td>
<td>在网络分区的情况下，被分隔的节点仍能正常对外提供服务 <!-- raw HTML omitted --> (分布式集群，数据被分布存储在不同的服务器上，无论什么情况，服务器都能正常被访问)</td>
</tr>
</tbody>
</table>
<p>定律：任何分布式系统只可同时满足二点，没法三者兼顾。</p>
<table>
<thead>
<tr>
<th>选择、放弃</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>CA，放弃P</td>
<td>如果想避免分区容错性问题的发生，一种做法是将所有的数据(与事务相关的)都放在一台机器上。<!-- raw HTML omitted --> 虽然无法100%保证系统不会出错，单不会碰到由分区带来的负面效果。当然这个选择会严重的影响系统的扩展性。</td>
</tr>
<tr>
<td>CP，放弃A</td>
<td>相对于放弃&quot;分区容错性&quot;来说，其反面就是放弃可用性。<!-- raw HTML omitted --> 一旦遇到分区容错故障，那么受到影响的服务需要等待一定时间，因此在等待时间内系统无法对外提供服务。</td>
</tr>
<tr>
<td>AP，放弃C</td>
<td>这里所说的放弃一致性，并不是完全放弃数据一致性，而是放弃数据的强一致性，而保留数据的最终一致性。<!-- raw HTML omitted --> 以网络购物为例，对只剩下一件库存的商品，如果同时接受了两个订单，那么较晚的订单将被告知商品告罄。</td>
</tr>
</tbody>
</table>
<h2 id="zookeeper-与-eureka-的区别">Zookeeper 与 Eureka 的区别</h2>
<table>
<thead>
<tr>
<th>对比项</th>
<th>Zookeeper</th>
<th>Eureka</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>CAP</td>
<td>CP</td>
<td>AP</td>
<td></td>
</tr>
<tr>
<td>Dubbo 集成</td>
<td>已支持</td>
<td>-</td>
<td></td>
</tr>
<tr>
<td>Spring Cloud 集成</td>
<td>已支持</td>
<td>已支持</td>
<td></td>
</tr>
<tr>
<td>kv 服务</td>
<td>已支持</td>
<td>-</td>
<td>ZK 支持数据存储，eureka不支持</td>
</tr>
<tr>
<td>使用接口(多语言能力)</td>
<td>提供客户端</td>
<td>http 多语言</td>
<td>ZK 的跨语言支持比较弱</td>
</tr>
<tr>
<td>watch 支持</td>
<td>支持</td>
<td>支持</td>
<td>什么是Watch 支持？就是客户单监听服务端的变化情况。<!-- raw HTML omitted --> zk 通过订阅监听来实现，eureka通过轮询的方式来实现</td>
</tr>
<tr>
<td>集群监控</td>
<td>-</td>
<td>metrics</td>
<td>metrics，运维者可以收集并报警这些度量信息达到监控目的</td>
</tr>
</tbody>
</table>
<h1 id="eureka自我保护">Eureka自我保护</h1>
<h2 id="什么是自我保护">什么是自我保护？</h2>
<p>一般情况下，微服务在Eureka 上注册后，会每30 秒发送心跳包，Eureka 通过心跳来
判断服务时候健康，同时会定期删除超过90 秒没有发送心跳服务。</p>
<p>有两种情况会导致Eureka Server 收不到微服务的心跳</p>
<ul>
<li>微服务自身的原因</li>
<li>微服务与Eureka 之间的网络故障</li>
</ul>
<p>通常(微服务的自身的故障关闭)只会导致个别服务出现故障，一般不会出现大面积故障，而(网络故障)通常会导致Eureka Server 在短时间内无法收到大批心跳。</p>
<p>考虑到这个区别，Eureka 设置了一个阀值，当判断挂掉的服务的数量超过阀值时，Eureka Server 认为很大程度上出现了网络故障，将不再删除心跳过期的服务。</p>
<p>那么这个阀值是多少呢？</p>
<p>15 分钟之内是否低于85%；</p>
<p>Eureka Server 在运行期间，会统计心跳失败的比例在15 分钟内是否低于85%，这种算法叫做Eureka Server的自我保护模式。</p>
<h2 id="为什么要启动自我保护">为什么要启动自我保护</h2>
<ol>
<li>因为同时保留&quot;好数据&quot;与&quot;坏数据&quot;总比丢掉任何数据要更好，当网络故障恢复后，
这个Eureka 节点会退出&quot;自我保护模式&rdquo;。</li>
<li>Eureka 还有客户端缓存功能(也就是微服务的缓存功能)。即便Eureka 集群中所有节点
都宕机失效，微服务的Provider 和Consumer
都能正常通信。</li>
<li>微服务的负载均衡策略会自动剔除死亡的微服务节点。</li>
</ol>
<h2 id="如何关闭自我保护">如何关闭自我保护</h2>
<p>修改 Eureka Server 配置文件（在服务端做，也就是注册中心的两个集群项目全局配置文件，而不是provider/consumer项目的配置文件）</p>
<pre><code class="language-properties">#关闭自我保护:true 为开启自我保护，false 为关闭自我保护
eureka.server.enableSelfPreservation=false
#清理间隔(单位:毫秒，默认是60*1000)
eureka.server.eviction.interval-timer-in-ms=60000
</code></pre>
<h1 id="如何优雅停服">如何优雅停服</h1>
<p>1）在客户端做，而不需要在 Eureka Server 中配置关闭自我保护</p>
<p>2）需要在服务中添加actuator.jar 包</p>
<pre><code class="language-xml">        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka-server&lt;/artifactId&gt;
        &lt;/dependency&gt;
</code></pre>
<p>图示如下：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708111924.png" alt=""></p>
<p>3）修改配置文件</p>
<pre><code class="language-properties">#启用shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false
</code></pre>
<p>4）发送一个关闭服务的URL请求</p>
<p>需添加一个依赖</p>
<pre><code class="language-xml">    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;
        &lt;artifactId&gt;httpclient&lt;/artifactId&gt;
        &lt;version&gt;4.5&lt;/version&gt;
    &lt;/dependency&gt;
</code></pre>
<pre><code class="language-java">public class HttpClientUtil {

	public static String doGet(String url, Map&lt;String, String&gt; param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = &quot;&quot;;
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), &quot;UTF-8&quot;);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map&lt;String, String&gt; param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = &quot;&quot;;
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List&lt;NameValuePair&gt; paramList = new ArrayList&lt;&gt;();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,&quot;utf-8&quot;);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), &quot;utf-8&quot;);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}
	
	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = &quot;&quot;;
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), &quot;utf-8&quot;);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}
	
	public static void main(String[] args) {
		String url =&quot;http://127.0.0.1:9090/shutdown&quot;;
		//该url必须要使用dopost方式来发送
		HttpClientUtil.doPost(url);
	}
}
</code></pre>
<p>也就是运行 HttpClientUtil#main方法，修改好ip、端口即可</p>
<h1 id="eureka-注册中心的安全认证">Eureka 注册中心的安全认证</h1>
<p>这里说的是服务端的安全认证，需要用户名、密码</p>
<p>这样做的目的：防止外部用户可以直接通过浏览器访问集群的后台页面 http://localhost:8761</p>
<p>1）添加security包</p>
<pre><code class="language-xml">    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
    &lt;/dependency&gt;
</code></pre>
<p>2）全局配置文件</p>
<pre><code class="language-properties">#开启http basic 的安全认证
security.basic.enabled=true
security.user.name=user
security.user.password=123456
</code></pre>
<p>3）修改访问集群节点的url</p>
<p>因为使用了密码，群节点之间的访问需要自带用户名密码</p>
<pre><code>eureka.client.service-url.defaultZone=http://user:123456@eureka1:8761/eureka/
</code></pre>
<p>格式是：<code>用户名:密码@</code></p>
<p>示例：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708111949.png" alt=""></p>
<p>eureka1：</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8761

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka1
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://user:123456@eureka2:8762/eureka/

#开启http basic 的安全认证
security.basic.enabled=true
security.user.name=user
security.user.password=123456
</code></pre>
<p>eureka2：</p>
<pre><code class="language-properties">spring.application.name=eureka-server
server.port=8762

#设置eureka实例名称，与配置文件的变量为主
eureka.instance.hostname=eureka2
#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://user:123456@eureka1:8761/eureka/

#开启http basic 的安全认证
security.basic.enabled=true
security.user.name=user
security.user.password=123456
</code></pre>
<p>4）微服务与注册中心之间的通讯也需要自带用户名和密码</p>
<p>如 eureka-provider 微服务</p>
<pre><code class="language-properties">spring.application.name=eureka-provider
server.port=9090

#设置服务注册中心地址，指向另一个注册中心
eureka.client.service-url.defaultZone=http://user:123456@eureka1:8761/eureka/,user:123456@http://eureka2:8762/eureka/

#启用shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false
</code></pre>
<p>其它微服务也需要自动用户名、密码</p>
<p>5）效果</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708112046.png" alt=""></p>
<h1 id="q--a">Q &amp; A</h1>
<h2 id="no-main-manifest-attribute">no main manifest attribute</h2>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708112059.png" alt=""></p>
<p>原因，需要在子module模块的pom.xml文件中添加插件依赖：</p>
<pre><code class="language-xml">    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;!-- 指定该Main Class为全局的唯一入口 --&gt;
                    &lt;mainClass&gt;com.swapping.springcloud.ms.eureka.SpringcloudMsEurekaApplication&lt;/mainClass&gt;
                    &lt;layout&gt;ZIP&lt;/layout&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;repackage&lt;/goal&gt;&lt;!--可以把依赖的包都打包到生成的Jar包中--&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
</code></pre>
<p>参考：https://www.cnblogs.com/sxdcgaq8080/p/10130621.html</p>
<hr>
<p>其它学习资料《重新定义Spring Cloud实战.pdf》</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-2-eureka/" title="Java-framework-SpringCloud-2-Eureka" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-2-eureka/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-1/" title="Java-framework-SpringCloud-1"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-3/"
                    title="Java-framework-SpringCloud-3"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
